package com.galengao.springboot.eventlistener.service;

import com.galengao.springboot.eventlistener.dao.UserDao;
import com.galengao.springboot.eventlistener.dto.SimpleMailDto;
import com.galengao.springboot.eventlistener.dto.UserDto;
import com.galengao.springboot.eventlistener.entity.User;
import com.galengao.springboot.eventlistener.event.CouponEvent;
import com.galengao.springboot.eventlistener.event.MailEvent;
import com.galengao.springboot.eventlistener.event.MessageEvent;
import com.galengao.springboot.eventlistener.mapper.UserMapper;
import com.galengao.springboot.validateAndResponse.resp.BaseResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.UUID;

/**
 * 用户接口实现
 *
 * @author galenGao
 * @version Id: UserServiceImpl.java, v 0.1 2022/7/21 21:13  GalenGao Exp $$
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService, ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;

    private final ApplicationContext applicationContext;

    private final UserMapper userMapper;

    private final UserDao userDao;

    @Override
    @Transactional
    public BaseResponse<String> register(UserDto userDto) {
        User user = userMapper.toEntity(userDto);
        User entity = userDao.save(user);
        SimpleMailDto mailDto = SimpleMailDto.builder().from("新晨").to(entity.getEmail()).subject("用户注册激活")
                .text("激活验证码：" + UUID.randomUUID().toString().substring(0, 6)).build();
        // 发送激活事件
        applicationEventPublisher.publishEvent(new MailEvent(this,mailDto));

        // 发送短信
        String username = user.getUsername();
        applicationContext.publishEvent(new MessageEvent(this,"恭喜你！注册系统成功.", username));
        // 赠送优惠劵
        applicationContext.publishEvent(new CouponEvent(this,new BigDecimal("20"),username));
        this.doExtra();
        return BaseResponse.success();
    }



    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 模拟做其他业务逻辑并抛出异常
     */
    private void doExtra() {
        throw new RuntimeException("出错啦！");
    }
}
